<template>
  <div id="allmap" ref="allmap"></div>
</template>

<script>
import config from '@/defaultSettings'
import '../../../../public/offlinemap/tools/DrawingManager_min.css'
function ComplexCustomOverlay(point, html) {
  this._point = point
  this._html = html
}
ComplexCustomOverlay.prototype = new BMap.Overlay()
ComplexCustomOverlay.prototype.initialize = function(map) {
  this._map = map
  var div = (this._div = document.createElement('div'))
  div.setAttribute('class', 'marker')
  div.innerHTML = this._html

  this._map.getPanes().labelPane.appendChild(div)
  return div
}
ComplexCustomOverlay.prototype.draw = function() {
  var map = this._map
  var pixel = map.pointToOverlayPixel(this._point)
  this._div.style.left = pixel.x + 'px'
  this._div.style.top = pixel.y + 'px'
}
export default {
  props: {
    isToolShow: {
      type: Boolean,
      default: false
    },
    isAddLine: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      map: null,
      chartVOList: [],
      overlays: [],
      chartStyleOptions: {
        strokeColor: '#1890FF', // 边线颜色。
        fillColor: '#1890FF', // 填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 2, // 边线的宽度，以像素为单位。
        strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
        fillOpacity: 0.3, // 填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' // 边线的样式，solid或dashed
      },
      positionArr: []
    }
  },
  mounted() {
    this.drawMap()
    // this.setMapData()
  },
  methods: {
    drawMap() {
      const _this = this
      // 禁用百度地图景点弹窗 enableMapClick: false
      this.map = new window.BMap.Map(this.$refs.allmap, { enableMapClick: false }) // 创建Map实例
      this.map.centerAndZoom(new window.BMap.Point(config.initLng, config.initLat), 14) // 初始化地图,设置中心点坐标和地图级别
      // this.map.addControl(
      //   new window.BMap.MapTypeControl({
      //     // 添加地图类型控件
      //     mapTypes: [window.BMAP_NORMAL_MAP, window.BMAP_HYBRID_MAP]
      //   })
      // )
      this.map.setCurrentCity('海口') // 设置地图显示的城市 此项是必须设置的
      this.map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
      this.map.enableAutoResize() // 启用自动适应容器尺寸变化
      // 框选工具
      if (this.isToolShow) {
        // 绘制工具事件
        _this.overlays = []

        let overlaycomplete = function(e) {
          const drawMode = e.drawingMode
          _this.clearAll()
          _this.overlays.push(e.overlay)
          _this.chartVOList = []

          if (drawMode === 'circle') {
            // 圆形
            let circle = e.overlay
            let center = circle.getCenter()
            let radius = circle.getRadius()
            _this.chartVOList.push({
              longitude: center.lng,
              latitude: center.lat,
              radius: radius.toString()
            })
          } else {
            // 多边形
            let path = e.overlay.getPath() // Array<Point> 返回多边型的点数组
            for (let i = 0; i < path.length; i++) {
              _this.chartVOList.push({ longitude: path[i].lng, latitude: path[i].lat })
            }
          }
          _this.$emit('getPoint', _this.chartVOList)
        }
        // 实例化鼠标绘制工具
        _this.drawingManager = new BMapLib.DrawingManager(_this.map, {
          isOpen: false, // 是否开启绘制模式
          enableDrawingTool: true, // 是否显示工具栏
          drawingToolOptions: {
            anchor: window.BMAP_ANCHOR_TOP_RIGHT, // 位置
            offset: new BMap.Size(5, 5), // 偏离值
            drawingModes: [window.BMAP_DRAWING_POLYGON, window.BMAP_DRAWING_CIRCLE, window.BMAP_DRAWING_RECTANGLE]
          },
          circleOptions: _this.chartStyleOptions, // 圆的样式
          polylineOptions: _this.chartStyleOptions, // 线的样式
          polygonOptions: _this.chartStyleOptions, // 多边形的样式
          rectangleOptions: _this.chartStyleOptions // 矩形的样式
        })
        // 添加鼠标绘制工具监听事件，用于获取绘制结果
        _this.drawingManager.addEventListener('overlaycomplete', overlaycomplete)
      }
    },
    // 输入模糊搜索信息
    getPositionList(str) {
      let that = this
      var options = {
        onSearchComplete: function(results) {
          // 判断状态是否正确
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              // console.log(results.getPoi(i))
              let obj = {
                key: i,
                title: results.getPoi(i).title,
                address: results.getPoi(i).address,
                longitude: results.getPoi(i).point.lng,
                latitude: results.getPoi(i).point.lat
              }
              s.push(obj)
            }
            console.log('s')
            console.log(s)
            that.$emit('pisitionList', s)
            let arr = [{ list: s }]
            // setTimeout(() => {
            that.drawTask(arr)
            // }, 1000)
            // document.getElementById('r-result').innerHTML = s.join('<br/>')
          } else {
            that.$emit('pisitionList', []) // 没查询到数据返回空数组
          }
        }
      }
      var local = new BMap.LocalSearch(that.map, options)
      local.search(str)
    },
    // 根据地址得到坐标
    searchByName(str) {
      // 创建地址解析器实例
      var myGeo = new window.BMap.Geocoder()
      // 将地址解析结果显示在地图上，并调整地图视野
      let that = this
      myGeo.getPoint(
        str,
        function(point) {
          // console.log('point')
          // console.log(point)
          if (point) {
            let arr = [
              [
                {
                  key: 0,
                  longitude: point.lng,
                  latitude: point.lat
                }
              ]
            ]
            that.setMapData(arr)
            // that.$emit('getPoint', point)
          } else {
            alert('您选择的地址没有解析到结果！')
          }
        },
        '北京市'
      )
    },
    // 根据坐标得到地址描述
    searchByPoint(pObj) {
      // 创建地址解析器实例
      var myGeo = new window.BMap.Geocoder()
      // 将地址解析结果显示在地图上，并调整地图视野
      let that = this
      // 根据坐标得到地址描述
      myGeo.getLocation(new window.BMap.Point(pObj.selectionVos[0].longitude, pObj.selectionVos[0].latitude), function(
        result
      ) {
        if (result) {
          // console.log(result)
          that.$emit('getAddress', result)
          let arr = [
            [
              {
                key: 0,
                longitude: result.point.lng,
                latitude: result.point.lat,
                address: result.surroundingPois[0].address
              }
            ]
          ]
          that.setMapData(arr)
        }
      })
    },
    // 打点,轨迹,对外开放接口
    setMapData(arr) {
      // let arr1 = [
      //   {
      //     key: 0,
      //     longitude: '110.34088',
      //     latitude: '20.035595',
      //     position: '的开发商111',
      //   },
      //   {
      //     key: 1,
      //     longitude: '110.35066',
      //     latitude: '20.039592',
      //     position: '的开发商222',
      //   },
      //   {
      //     key: 2,
      //     longitude: '110.35061',
      //     latitude: '20.007817',
      //     position: '的开发商333',
      //   }
      // ]
      // let arr2 = [
      //   {
      //     key: 0,
      //     longitude: '110.24088',
      //     latitude: '20.033595',
      //     position: '的开发商111',
      //   },
      //   {
      //     key: 1,
      //     longitude: '110.25161',
      //     latitude: '20.030592',
      //     position: '的开发商222',
      //   },
      //   {
      //     key: 2,
      //     longitude: '110.25061',
      //     latitude: '20.001817',
      //     position: '的开发商333',
      //   }
      // ]
      // let listArr = [{ list: arr1 },{ list: arr2 }]
      let listArr = []
      if (arr && arr.length > 0) {
        arr.forEach(itemArr => {
          listArr.push({ list: itemArr })
          // 网格员走访轨迹使用到
          if (itemArr[0].sysUserId != undefined) {
            this.positionArr.push({
              id: itemArr[0].sysUserId,
              longitude: itemArr[0].longitude,
              latitude: itemArr[0].latitude
            })
          }
        })
      } else {
        this.$message.warning('没有点信息')
      }
      setTimeout(() => {
        this.drawTask(listArr)
      }, 500)
    },
    // 根本数据输出标准轨迹
    drawTask(data) {
      // this.isLoading = false // 隐藏查询提示
      const colors = ['red', 'blue', 'green', 'violet', 'deongaree', 'orange']
      // this.getRepeatPointer(data)
      this.map.clearOverlays()
      data.forEach((item, index) => {
        this.drawOverlay(item.list, colors[index])
        // 匹配到的轨迹标注序号
        // if (index !== 0) {
        //   const point = new BMap.Point(item.list[0].longitude, item.list[0].latitude)
        //   const html = `<span class="tip ${colors[index]}">${item.key + 1}号轨迹</span>`
        //   const myCompOverlay = new ComplexCustomOverlay(point, html)
        //   this.map.addOverlay(myCompOverlay)
        // }
      })
      this.panTo(data[data.length - 1].list, 0)
    },
    getRepeatPointer(data) {
      let latitudeLongitude = []
      let isRepeatLaLoList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (latitudeLongitude.includes(s)) {
              isRepeatLaLoList.push(s)
              return
            }
            latitudeLongitude.push(s)
          })
        }
      })
      let l = []
      let repeatLineList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach((v, i2) => {
            v.listIndex = index
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (isRepeatLaLoList.includes(s)) {
              let i = isRepeatLaLoList.indexOf(s)
              let time = new Date(v.arriveTime).Format('yyyy-MM-dd hh:mm:ss')
              v.isRepeat = true
              if (l.map(v1 => v1.index).includes(i)) {
                let y = l.map(v2 => v2.index).indexOf(i)
                // v.text = l[y].text + `\n【${i2 + 1}】${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.text = l[y].text + `\n ${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.index = l[y].index
                v.flag = v.flag || l[y].flag
                if (v.listIndex !== l[y].listIndex) {
                  v.repeatLine = true
                  repeatLineList.push(s)
                }
                l[y] = Object.assign({}, v)
                return
              }
              l.push({
                index: i,
                text: ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`,
                flag: v.flag,
                listIndex: v.listIndex
              })
              v.text = ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`
            }
          })
        }
      })
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (repeatLineList.includes(s)) {
              v.repeatLine = true
            }
          })
        }
      })
    },
    drawOverlay(data, type) {
      if (this.isAddLine) {
        this.addLine(data, type)
      }
      this.addMarker(data)
    },
    addMarker(data) {
      // console.log('data')
      // console.log(data)
      let that = this
      data.forEach((item, index) => {
        const point = new BMap.Point(item.longitude, item.latitude)
        let html = `<span class="sign">` + (index + 1) + `</span>`
        let marker = new BMap.Marker(point)
        const myCompOverlay = new ComplexCustomOverlay(point, html)
        this.map.addOverlay(marker)
        this.map.addOverlay(myCompOverlay)
        let label = new BMap.Label(
          '<div class="markerTipBox"><p>' +
            '<span class="s1">位置：</span>' +
            '<span class="s2">' +
            item.address +
            '</span>' +
            '</p><p>' +
            '<span class="s1">经度：</span>' +
            '<span class="s2">' +
            item.longitude +
            '<span>' +
            '</p><p>' +
            '<span class="s1">纬度：</span>' +
            '<span class="s2">' +
            item.latitude +
            '<span>' +
            '</p></div>',
          {
            offset: new BMap.Size(20, -110)
          }
        )
        marker.setLabel(label)
        // 初始化不显示
        label.setStyle({
          display: 'none'
        })
        // 设置标注点在覆盖物上面,设置marker层级
        that.map.getPanes().markerPane.style.zIndex = 500
        // 鼠标点击时
        marker.addEventListener('mousedown', function(e) {
          that.$emit('markerClick', '1111')
        })
        // 鼠标经过时
        marker.addEventListener('mouseover', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'block'
          })
        })
        // 鼠标离开时
        marker.addEventListener('mouseout', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'none'
          })
        })
      })
    },
    addLine(data, type) {
      const colors = {
        red: '#d91f1b',
        blue: '#009dd9',
        // blue: "#2F98F4",
        green: '#48bb00',
        violet: '#762bd0',
        deongaree: '#1921b3',
        orange: 'orange'
      }
      let line = []
      data.forEach((item, index) => {
        line.push(new BMap.Point(item.longitude, item.latitude))
      })
      // console.log('line')
      // console.log(line)
      var polyline = new BMap.Polyline(line, {
        strokeColor: colors[type],
        strokeWeight: 2.5,
        strokeOpacity: 0.8
      }) // 创建折线
      this.map.addOverlay(polyline) // 增加折线
    },
    panTo(data, key) {
      const target = data.filter(item => key === item.key)[0]
      target && this.map.panTo(new BMap.Point(target.longitude, target.latitude))
    },
    clearOverlays() {
      this.map.clearOverlays()
    },
    clearAll() {
      if (this.overlays.length > 0) {
        for (var i = 0; i < this.overlays.length; i++) {
          this.map.removeOverlay(this.overlays[i])
        }
      }
      this.overlays.length = 0
    },
    // 回显渲染框选区域
    onChartVOList(obj) {
      this.map.clearOverlays()
      let chartVOList = obj.chartVOList
      let point = []
      let chartObjet = null

      for (let i = 0, len = chartVOList.length; i < len; i++) {
        point.push(new BMap.Point(chartVOList[i].longitude, chartVOList[i].latitude))
      }

      if (chartVOList.length > 1) {
        // 多边形
        chartObjet = new BMap.Polygon(point, this.chartStyleOptions)
      } else {
        // 圆形
        chartObjet = new BMap.Circle(point[0], chartVOList[0].radius, this.chartStyleOptions)
      }
      this.overlays = [chartObjet]
      this.map.addOverlay(chartObjet)
      this.map.panTo(point[0])
    },
    // 网格员走访轨迹使用到
    onSelect(id) {
      let num = 0
      let len = this.positionArr.length
      this.positionArr.forEach((item, index) => {
        // 利用id的唯一性，找出选中人员的轨迹点,并移动改点到地图中间
        // console.log(item.id,id)
        if (item.id == id) {
          this.map.panTo(new BMap.Point(this.positionArr[index].longitude, this.positionArr[index].latitude))
        } else {
          num++
        }
      })
      if (num == len) {
        this.$message.warning('无轨迹点信息')
      }
    }
  }
}
</script>

<style lang="less" scoped>
#allmap {
  // height: 700px;
  height: 100%;
  overflow: hidden;
}
</style>
<style lang="less">
.markerTipBox {
  position: absolute;
  left: -330px;
  z-index: 100000;
  border: none !important;
  z-index: 99999;
  background: rgba(255, 255, 255, 1);
  color: #666;
  font-size: 14px;
  padding: 10px 20px;
  line-height: 20px;
  width: 300px;
  white-space: normal;
  border-radius: 5px;
  .s1 {
    // margin-left: 30px;
    // width: 90px;
    display: inline-block;
    text-align: right;
  }
  .s2 {
    margin-left: 5px;
  }
}
.marker {
  position: absolute;
  height: 40px;
  transform: translate(-50%, -100%);
  &.active {
    z-index: 1000;
    .info {
      display: block;
    }
  }
}
.sign {
  display: block;
  width: 30px;
  height: 40px;
  line-height: 30px;
  text-align: center;
  font-size: 15px;
  color: #fff;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
  background-image: url('./img/marker_red2.png') !important;
  cursor: pointer;
}
//设置标注点
.BMap_Marker {
  // width: 200px!important;
  // height: 200px!important;
  // background-size: 100% 100%!important;
  img {
    display: none !important;
    // width: 400px;
    // height: 400px;
  }
}
//百度地图左下角标志隐藏
.anchorBL {
  display: none;
}
/deep/.BMapLib_Drawing {
  // inset: 5px auto auto 5px !important;
  position: absolute !important;
  left: 5px !important;
  top: 5px !important;
}
</style>
